package com.mlnx.device.session.manager;

import com.mlnx.common.utils.MyLog;

import org.shan.mq.session.core.Session;
import org.shan.spring.redis.RedisUtil;

import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * Created by amanda.shan on 2019/11/25.
 */
public class RedisSessionManager extends MutilDeviceSessionManager {

    MyLog log = MyLog.getLog(getClass());

    private RedisUtil redisUtil;

    private String onlineDeviceKey;

    public RedisSessionManager(RedisUtil redisUtil, String onlineDeviceKey) {
        this.redisUtil = redisUtil;
        this.onlineDeviceKey = onlineDeviceKey;
    }

    @Override
    public Collection<String> getEcgDeviceIds() {

        Set keys = redisUtil.getRedisTemplate().opsForHash().keys(onlineDeviceKey);

        return keys;
    }

    @Override
    public Collection<String> getOnlineDeviceIds(Collection<String> askDeviceIds) {

        Set keys = redisUtil.getRedisTemplate().opsForHash().keys(onlineDeviceKey);
        List<String> onlineDeviceIds =
                askDeviceIds.stream().filter(deviceId -> keys.contains(deviceId)).collect(Collectors.toList());

        return onlineDeviceIds;
    }

    @Override
    public synchronized void addSession(Session session) {
        super.addSession(session);

        redisUtil.hset(onlineDeviceKey, session.getClientId(), session);
    }

    @Override
    public synchronized void removeSession(Session session) {
        super.removeSession(session);

        if (session != null) {
            redisUtil.hdel(onlineDeviceKey, session.getClientId());
        }
    }

    public void clear() {
        redisUtil.del(onlineDeviceKey);

        log.info("清除在线心电设备redis缓存");
    }
}
